package com.swf.seed.os.command.impl;

import java.io.File;
import java.io.IOException;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.io.FileUtils;

import com.swf.seed.base.SdLetter;
import com.swf.seed.os.annotation.Command;

/**
 * Copy file 
 *
 * @author Weifeng Shen
 * @since 2016年7月20日
 * @see CommandAdaptor
 */
@Command("cp")
public class CopyCommand extends CommandAdaptor{
		
	@Override
	public void option() {
		options.addOption(SdLetter.r, "recursive", false, "copy files and directories");  
		options.addOption(Option.builder(SdLetter.s).longOpt("source").argName("file" )
				.hasArg().desc("source File to copy" ).numberOfArgs(1).required().build());  
		options.addOption(Option.builder(SdLetter.t).longOpt("target").argName("file" )
				.hasArg().desc("target File to copy" ).numberOfArgs(1).required().build()); 
	}

	@Override
	void customizedExecute(CommandLine commandLine) throws ParseException, IOException {
		File sourceFile = null;
		if (commandLine.hasOption(SdLetter.s)){
			String path = commandLine.getOptionValue(SdLetter.s);
			sourceFile = new File(path);
			if (!sourceFile.exists()){
				throw new ParseException(String.format("source file %s not existed",path));
			}
		}
		
		File targetFile = null;
		if (commandLine.hasOption(SdLetter.t)){
			String path = commandLine.getOptionValue(SdLetter.t);
			targetFile = new File(path);
		}
		System.out.println(String.format("copy  %s to %s", sourceFile.getAbsolutePath(),targetFile.getAbsolutePath()));
		if (commandLine.hasOption(SdLetter.r)){
			if (!targetFile.exists()){
				targetFile.mkdirs();
			}
			FileUtils.copyDirectory(sourceFile, targetFile);
		}else {
			if (!targetFile.getParentFile().exists()){
				targetFile.getParentFile().mkdirs();
			}
			FileUtils.copyFile(sourceFile, targetFile);
		}
	}
	
}
